<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form :form="form" slot="detail">
        <a-card title="业务信息" size="small">
          <a-row>
            <a-col :span="12">
              <a-form-item label="公司名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <!--              <j-dict-select-tag type="list" v-decorator="['companyName']" :trigger-change="true" dictCode=""-->
                <!--                                 placeholder="请选择公司名称" />-->
                <!--              <a-select v-decorator="['companyName', validatorRules.companyName]" placeholder="请选择公司名称">-->
                <!--                &lt;!&ndash;                <div slot="dropdownRender" slot-scope="menu">&ndash;&gt;-->
                <!--                &lt;!&ndash;                  <v-nodes :vnodes="menu" />&ndash;&gt;-->
                <!--                &lt;!&ndash;                  <a-divider style="margin: 4px 0;" />&ndash;&gt;-->
                <!--                &lt;!&ndash;                  <div&ndash;&gt;-->
                <!--                &lt;!&ndash;                    style="padding: 4px 8px; cursor: pointer;"&ndash;&gt;-->
                <!--                &lt;!&ndash;                    @mousedown="e => e.preventDefault()"&ndash;&gt;-->
                <!--                &lt;!&ndash;                    @click="addItem"&ndash;&gt;-->
                <!--                &lt;!&ndash;                  >&ndash;&gt;-->
                <!--                &lt;!&ndash;                    <a-icon type="plus-circle" />&ndash;&gt;-->
                <!--                &lt;!&ndash;                    添加新客户&ndash;&gt;-->
                <!--                &lt;!&ndash;                  </div>&ndash;&gt;-->
                <!--                &lt;!&ndash;                </div>&ndash;&gt;-->
                <!--                <a-select-option v-for="(item, key) in dictOptions" :key="key" :value="item.value">-->
                <!--                  {{ item.text }}-->
                <!--                </a-select-option>-->
                <!--              </a-select>-->
                <a-select v-decorator="['companyName', validatorRules.companyName]" allowClear showSearch
                          placeholder="请选择公司名称">
                  <a-select-option v-for="(item, key) in companyData" :key="key" :value="item.value">
                    {{ item.text }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="箱东代码" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-auto-complete allowClear v-decorator="['containerCode']" placeholder="箱东代码"
                                 :dataSource="socOptions" :filterOption="containerCodeFilterOption" />
                <!--              <j-popup-->
                <!--                v-decorator="['containerCode']"-->
                <!--                :trigger-change="true"-->
                <!--                org-fields="id,container_code,container_number,container_type"-->
                <!--                dest-fields="boxId,containerCode,containerNumber,containerType"-->
                <!--                code="jzx_info"-->
                <!--                @callback="popupCallback" />-->
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="箱号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input v-decorator="['containerNumber']"
                         placeholder="箱号"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="箱型" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <!--              <a-input v-decorator="['containerType']"-->
                <!--                       placeholder="箱型"></a-input>-->
                <j-dict-select-tag @change="getBoxType" v-decorator="['containerType']" placeholder="箱型"
                                   dictCode="box_type" :triggerChange="true" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="客户业务编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input v-decorator="['customerBusinessNumber']" placeholder="请输入客户业务编号"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="新箱/旧箱" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <j-dict-select-tag type="radio" v-decorator="['conditionType']" :trigger-change="true"
                                   dictCode="box_condition" placeholder="请选择新箱/旧箱" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="起运港" :labelCol="labelCol"
                           :wrapperCol="wrapperCol">
                <a-row>
                  <a-col :span="8">
                    <a-select
                      label-in-value
                      v-decorator="['pol',{initialValue: {value:'CNTAO',key:'CNTAO'}}]"
                      placeholder="选择起运港"
                      style="width: 100%"
                      :filter-option="false"
                      show-search
                      allowClear
                      @search="searchPort"
                      @select="portDataChangePol"
                      :dropdownMatchSelectWidth="false"
                      :getPopupContainer="
                        triggerNode => {
                          return triggerNode.parentNode || document.body;
                        }
                      "
                    >
                      <a-select-option v-for="(d,key) in portData" :value="d.value">
                        {{ d.text }}
                      </a-select-option>
                    </a-select>
                  </a-col>
                  <a-col :span="16">
                    <a-input v-decorator="['polDesc']"></a-input>
                  </a-col>
                </a-row>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="目的港" :labelCol="labelCol"
                           :wrapperCol="wrapperCol">
                <a-row>
                  <a-col :span="8">
                    <a-select
                      label-in-value
                      v-decorator="['pod']"
                      placeholder="选择目的港"
                      style="width: 100%"
                      :filter-option="false"
                      show-search
                      allowClear
                      @search="searchPort"
                      @select="portDataChangePod"
                      :dropdownMatchSelectWidth="false"
                      :getPopupContainer="
                        triggerNode => {
                          return triggerNode.parentNode || document.body;
                        }
                      "
                    >
                      <a-select-option v-for="(d,key) in portData" :value="d.value">
                        {{ d.text }}
                      </a-select-option>
                    </a-select>
                  </a-col>
                  <a-col :span="16">
                    <a-input v-decorator="['podDesc']"></a-input>
                  </a-col>
                </a-row>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="起运港进堆场时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <j-date placeholder="请选择起运港进堆场时间" v-decorator="['polInTime']" :trigger-change="true"
                        date-format="YYYY-MM-DD"
                        style="width: 100%" />
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item label="船公司" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <j-dict-select-tag v-decorator="['shipCompany']" :trigger-change="true"
                                   dictCode="ship_company" placeholder="船公司" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="ETD" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <j-date placeholder="请选择ETD" v-decorator="['etd']" :trigger-change="true" style="width: 100%"
                        date-format="YYYY-MM-DD" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="ETA" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <j-date placeholder="请选择ETA" v-decorator="['eta']" :trigger-change="true" style="width: 100%"
                        date-format="YYYY-MM-DD" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="目的港提货时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <j-date placeholder="目的港提货时间" v-decorator="['podDeliveryTime']" :trigger-change="true"
                        style="width: 100%"
                        date-format="YYYY-MM-DD" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="目的港还空箱时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <j-date placeholder="请选择目的港还空箱时间" v-decorator="['podReturnboxTime']" :trigger-change="true"
                        @change="getReturnBoxDate" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="目的港离场时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <j-date placeholder="请选择目的港离场时间" v-decorator="['podLeaveTime']" :trigger-change="true"
                        @change="getLevelDate" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="目的港堆存天数" :labelCol="labelCol" :wrapperCol="wrapperCol"
                           help="目的港堆存天数=目的港离场时间-目的港还空箱时间+1">
                <a-input disabled v-decorator="['podStackingDays']" placeholder=""
                         style="width: 100%;color: black;" suffix="DAYS(天)" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="目的港堆场信息" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-select v-decorator="['podYardInfo']"
                          placeholder="请选择堆场" allowClear showSearch :filter-option="filterOption"
                          @change="changeYardOption">
                  <a-select-option v-for="(item, key) in yardInfoOptions" :key="key" :value="item.value">
                    {{ item.text }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <!--            help="目的港堆场总费用= 目的港堆存天数 x 目的港堆场收费费率中的按天费用 + 其他按箱数收费的费用x箱数"-->
              <a-form-item label="目的港堆场总费用" :labelCol="labelCol" :wrapperCol="wrapperCol"
                           help="目的港堆场总费用=目的港堆场收费费率中各项按天收费的费用x目的港堆存天数 + 各项按箱数收费的费用x箱数 + 其他各项按照次数收费的费用x次数"
              >
                <a-row>
                  <a-col :span="10">
                    <a-input disabled v-decorator="['podYardTotalCost']" :placeholder="podYardTotalCostTips"
                             style="width: 100%;color: black;" class="plclass" :suffix="bizhong" />
                  </a-col>
                  <a-col :span="8">
                    <a-input-number @blur="calcProfit" placeholder="请输入" v-decorator="['podYardTotalCostDesc']"
                                    style="width: 100%"
                    />
                  </a-col>
                  <a-col :span="6">
                    <j-dict-select-tag @change="podCostSelectCurrency" v-decorator="['podYardTotalCostDescCurrency']"
                                       :trigger-change="true"
                                       dictCode="currency" placeholder="币种" />
                  </a-col>
                </a-row>

              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="买箱费" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-row>
                  <a-col :span="18">
                    <a-input-number placeholder="请输入" v-decorator="['buyBoxCost']"
                                    @blur="calcProfit"
                                    style="width: 100%" />
                  </a-col>
                  <a-col :span="6">
                    <j-dict-select-tag @change="buyBoxSelectCurrency" v-decorator="['buyBoxCostCurrency']"
                                       :trigger-change="true"
                                       dictCode="currency" placeholder="币种" />
                  </a-col>
                </a-row>

              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="用箱费" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-row>
                  <a-col :span="18">
                    <a-input-number placeholder="请输入" v-decorator="['useBoxCost']"
                                    @blur="calcProfit"
                                    style="width: 100%" />
                  </a-col>
                  <a-col :span="6">
                    <j-dict-select-tag @change="useBoxSelectCurrency" v-decorator="['useBoxCostCurrency']"
                                       :trigger-change="true"
                                       dictCode="currency" placeholder="币种" />
                  </a-col>
                </a-row>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="意向卖箱费" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-row>
                  <a-col :span="18">
                    <a-input-number placeholder="请输入" v-decorator="['intentionToSellBoxFeel']"
                                    style="width: 100%" />
                  </a-col>
                  <a-col :span="6">
                    <j-dict-select-tag v-decorator="['intentionToSellBoxFeelCurrency']" :trigger-change="true"
                                       dictCode="currency" placeholder="币种" />
                  </a-col>
                </a-row>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="卖箱费" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-row>
                  <a-col :span="18">
                    <a-input-number placeholder="请输入" v-decorator="['saleBoxCost']"
                                    @blur="calcProfit"
                                    style="width: 100%" />
                  </a-col>
                  <a-col :span="6">
                    <j-dict-select-tag @change="saleBoxSelectCurrency" v-decorator="['saleBoxCostCurrency']"
                                       :trigger-change="true"
                                       dictCode="currency" placeholder="币种" />
                  </a-col>
                </a-row>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="利润额" :labelCol="labelCol" :wrapperCol="wrapperCol"
                           help="利润额=卖箱费+用箱费-买箱费-目的港堆场总费用">
                <a-row>
                  <a-col :span="10">
                    <a-input disabled v-decorator="['profit']" placeholder="" :suffix="lirunbizhong"
                             style="width: 100%" :placeholder="profixTips" class="plclass" />
                  </a-col>
                  <a-col :span="8">
                    <a-input-number v-decorator="['profitDesc']" style="width: 100%" placeholder="请输入" />
                  </a-col>
                  <a-col :span="6">
                    <j-dict-select-tag v-decorator="['profitDescCurrency']" :trigger-change="true"
                                       dictCode="currency" placeholder="币种" />
                  </a-col>
                </a-row>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="操作员" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input v-decorator="['createBy']" placeholder=""></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24" style="margin-left: -12.5%">
              <a-form-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-textarea
                  v-decorator="['remark']"
                  placeholder="备注"
                  :auto-size="{ minRows: 3, maxRows: 5 }"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
      </a-form>
    </j-form-container>
    <!--    <a-modal-->
    <!--      title="添加新客户"-->
    <!--      :visible="customerModalVisible"-->
    <!--      :maskClosable="false"-->
    <!--      :confirm-loading='confirmLoading'-->
    <!--      @ok="addHandleOk"-->
    <!--      @cancel="addHandleCancel"-->
    <!--    >-->
    <!--      <a-input placeholder="请输入新客户公司抬头" v-model="newCustomerTitle" :allowClear=true></a-input>-->
    <!--    </a-modal>-->
    <!-- 子表单区域 -->
    <!--    <a-tabs v-model="activeKey" type="card" @change="handleChangeTabs">-->
    <!--      <a-tab-pane tab="目的港堆场收费费率" :key="refKeys[0]" :forceRender="true">-->
    <!--        <j-editable-table-->
    <!--          :ref="refKeys[0]"-->
    <!--          :loading="jzxDefaultCostDetailsTable.loading"-->
    <!--          :columns="jzxDefaultCostDetailsTable.columns"-->
    <!--          :dataSource="jzxDefaultCostDetailsTable.dataSource"-->
    <!--          :maxHeight="300"-->
    <!--          :disabled="formDisabled"-->
    <!--          :rowNumber="true"-->
    <!--          :rowSelection="true"-->
    <!--          :actionButton="true" />-->
    <a-card size="small" title="目的港堆场收费费率">
      <a-table
        style="margin-bottom: 50px;"
        :pagination="false"
        size="small"
        bordered
        :scroll="{x:500,y:300}"
        :loading="jzxDefaultCostDetailsTable.loading"
        :columns="jzxDefaultCostDetailsTable.columns"
        :dataSource="jzxDefaultCostDetailsTable.dataSource" />
    </a-card>

    <!--      </a-tab-pane>-->
    <!--      <template v-if="status">-->
    <!--        <a-tab-pane tab="应收明细" :key="refKeys[1]" :forceRender="true">-->
    <!--          <j-editable-table-->
    <!--            :ref="refKeys[1]"-->
    <!--            :loading="costInfoTableYs.loading"-->
    <!--            :columns="costInfoTableYs.columns"-->
    <!--            :dataSource="costInfoTableYs.dataSource"-->
    <!--            :disabledRows="disabledRowsYs"-->
    <!--            @cb="reloadChildTabData"-->
    <!--            :formModel="model"-->
    <!--            :createBillBtn="true"-->
    <!--            :maxHeight="300"-->
    <!--            :disabled="formDisabled"-->
    <!--            :rowNumber="true"-->
    <!--            :rowSelection="true"-->
    <!--            :actionButton="true">-->
    <!--            <template v-slot:feeNameYs="props">-->
    <!--              <a-select :default-value="props.text" allowClear showSearch style="width: 100%"-->
    <!--                        placeholder="请选择费用名称" @change="(value) => handleProChangeYs(value, props.rowId)">-->
    <!--                <a-select-option v-for="(item, key) in feeNameData" :value="item.value">-->
    <!--                  {{ item.text }}-->
    <!--                </a-select-option>-->
    <!--              </a-select>-->
    <!--            </template>-->
    <!--            <template v-slot:jsdwYs="props">-->
    <!--              <a-select :default-value="props.text" allowClear showSearch style="width: 100%"-->
    <!--                        placeholder="请选择结算单位" @change="(value) => handleProChangeYsJsdw(value, props.rowId)">-->
    <!--                <a-select-option v-for="(item, key) in companyData" :value="item.value">-->
    <!--                  {{ item.text }}-->
    <!--                </a-select-option>-->
    <!--              </a-select>-->
    <!--            </template>-->
    <!--          </j-editable-table>-->
    <!--        </a-tab-pane>-->
    <!--        <a-tab-pane tab="应付明细" :key="refKeys[2]" :forceRender="true">-->
    <!--          <j-editable-table-->
    <!--            :ref="refKeys[2]"-->
    <!--            :loading="costInfoTableYf.loading"-->
    <!--            :columns="costInfoTableYf.columns"-->
    <!--            :dataSource="costInfoTableYf.dataSource"-->
    <!--            :disabledRows="disabledRowsYf"-->
    <!--            @cb="reloadChildTabData"-->
    <!--            :formModel="model"-->
    <!--            :createBillBtn="true"-->
    <!--            :maxHeight="300"-->
    <!--            :disabled="formDisabled"-->
    <!--            :rowNumber="true"-->
    <!--            :rowSelection="true"-->
    <!--            :actionButton="true">-->
    <!--            <template v-slot:feeNameYf="props">-->
    <!--              <a-select :default-value="props.text" allowClear showSearch style="width: 100%"-->
    <!--                        placeholder="请选择费用名称" @change="(value) => handleProChangeYf(value, props.rowId)">-->
    <!--                <a-select-option v-for="(item, key) in feeNameData" :value="item.value">-->
    <!--                  {{ item.text }}-->
    <!--                </a-select-option>-->
    <!--              </a-select>-->
    <!--            </template>-->
    <!--            <template v-slot:jsdwYf="props">-->
    <!--              <a-select :default-value="props.text" allowClear showSearch style="width: 100%"-->
    <!--                        placeholder="请选择结算单位" @change="(value) => handleProChangeYfJsdw(value, props.rowId)">-->
    <!--                <a-select-option v-for="(item, key) in companyData" :value="item.value">-->
    <!--                  {{ item.text }}-->
    <!--                </a-select-option>-->
    <!--              </a-select>-->
    <!--            </template>-->
    <!--          </j-editable-table>-->
    <!--        </a-tab-pane>-->
    <!--      </template>-->
    <!--    </a-tabs>-->
  </a-spin>
</template>

<script>

import pick from 'lodash.pick'
import { getAction, httpAction } from '@/api/manage'
import { FormTypes, getRefPromise, VALIDATE_NO_PASSED, validateFormAndTables } from '@/utils/JEditableTableUtil'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
import JFormContainer from '@/components/jeecg/JFormContainer'
import JDate from '@/components/jeecg/JDate'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import { ajaxGetDictItems } from '@api/api'
import Vue from 'vue'

export default {
  name: 'JzxTradeForm',
  mixins: [JEditableTableMixin],
  components: {
    JFormContainer,
    JDate,
    JDictSelectTag,
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes
    }
  },
  data() {
    return {
      bizhong: '',//堆场总费用币种
      lirunbizhong: '',//利润额币种
      podYardTotalCostTips: '',
      profixTips: '',
      portData: [],//港口数据
      getPortDataUrl: '/box/dictPort/findbyname',
      socOptions: [],
      customerModalVisible: false,
      confirmLoading: false,
      newCustomerTitle: '',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 0,
      validatorRules: {
        containerNumber: {
          rules: [
            { required: true, message: '请输入箱号!' }
          ]
        },
        companyName: {
          rules: [
            { required: true, message: '请选择公司名称!' }
          ]
        },
        containerType: {
          rules: [
            { required: true, message: '请选择集装箱信息!' }
          ]
        }
        // buyBoxCost: {
        //   rules: [
        //     { required: false },
        //     { pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }
        //   ]
        // },
        // useBoxCost: {
        //   rules: [
        //     { required: false },
        //     { pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }
        //   ]
        // },
        // saleBoxCost: {
        //   rules: [
        //     { required: false },
        //     { pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }
        //   ]
        // }
      },
      refKeys: ['jzxDefaultCostDetails', 'costInfoYs', 'costInfoYf'],
      tableKeys: ['costInfoYs', 'costInfoYf'],
      activeKey: 'jzxDefaultCostDetails',
      disabledRowsYs: {},
      disabledRowsYf: {},
      // 目的港堆场收费费率
      jzxDefaultCostDetailsTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '费用名称',
            key: 'costName',
            align: 'center',
            dataIndex: 'costName',
            width: '200px'
          },
          {
            title: '单价',
            key: 'price',
            align: 'center',
            dataIndex: 'price',
            width: '200px'
          },
          {
            title: '计费单位1',
            key: 'unit1_dictText',
            align: 'center',
            dataIndex: 'unit1_dictText',
            width: '200px'
          },
          {
            title: '计费单位2',
            key: 'unit2_dictText',
            align: 'center',
            dataIndex: 'unit2_dictText',
            width: '200px'
          },
          {
            title: '币种',
            key: 'currency',
            align: 'center',
            dataIndex: 'currency',
            width: '200px'
          }
        ]
      },
      // 费用明细信息表
      costInfoTableYs: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '费用状态',
            key: 'status',
            type: FormTypes.normal,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '账单未建立'
          },
          {
            title: '费用名称',
            key: 'costName',
            type: FormTypes.slot,
            width: '200px',
            slotName: 'feeNameYs',
            // 表单验证规则
            validateRules: [
              {
                required: true, // 必填
                message: '${title}不能为空' // 提示的文本
              }
            ]
          },
          {
            title: '币种',
            key: 'currency',
            type: FormTypes.select,
            dictCode: 'currency',
            width: '100px',
            placeholder: '请输入${title}',
            isReload: true,
            // 表单验证规则
            validateRules: [
              {
                required: true, // 必填
                message: '${title}不能为空' // 提示的文本
              }
            ]
          },
          {
            title: '结算单位',
            key: 'settlementCompany',
            type: FormTypes.slot,
            slotName: 'jsdwYs',
            width: '200px',
            // 表单验证规则
            validateRules: [
              {
                required: true, // 必填
                message: '${title}不能为空' // 提示的文本
              }
            ]
          },
          {
            title: '计费单位',
            key: 'chargingUnit',
            dictCode: 'billing_unit',
            type: FormTypes.sel_search,
            width: '200px',
            placeholder: '请输入${title}',
            isReload: true,
            // 表单验证规则
            validateRules: [
              {
                required: true, // 必填
                message: '${title}不能为空' // 提示的文本
              }
            ]
          },
          {
            title: '数量',
            key: 'num',
            type: FormTypes.inputNumber,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '1',
            isCalc: true,
            buisName: 'costDetail',
            validateRules: [{ pattern: 'z', message: '${title}格式不正确' }]
          },
          {
            title: '单价',
            key: 'price',
            type: FormTypes.inputNumber,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '0',
            isCalc: true,
            buisName: 'costDetail',
            validateRules: [{ pattern: 'money', message: '${title}格式不正确' }]
          },
          {
            title: '总价',
            key: 'totalPrice',
            type: FormTypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '0',
            statistics: true
          },
          // {
          //   title: '总金额(CNY)',
          //   key: 'cnyAmount',
          //   type: FormTypes.normal,
          //   width: '100px',
          //   placeholder: '请输入${title}',
          //   defaultValue: '0'
          // },
          {
            title: '汇率',
            key: 'rate',
            type: FormTypes.input,
            width: '80px',
            isCalc: true,
            buisName: 'costDetail',
            placeholder: '${title}',
            defaultValue: '1',
            validateRules: [{ required: true, pattern: 'n', message: '${title}格式不正确' }]
          },
          {
            title: '开票汇率',
            key: 'invoiceRate',
            type: FormTypes.input,
            width: '150px',
            placeholder: '请输入${title}',
            defaultValue: '1',
            validateRules: [{ pattern: 'n', message: '${title}格式不正确' }]
          },
          {
            title: '账单类型',
            key: 'billType',
            type: FormTypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '应收'
          },
          // {
          //   title: '',
          //   key: 'type',
          //   type: FormTypes.normal,
          //   width: '0px',
          //   placeholder: '请输入${title}',
          //   defaultValue: 'ys',
          //   disabled:true
          // },
          {
            title: '账单号',
            key: 'billNumber',
            type: FormTypes.normal,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '发票号',
            key: 'invoiceNumber',
            type: FormTypes.normal,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '备注',
            key: 'remark',
            type: FormTypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          }
        ]
      },
      // 费用明细信息表
      costInfoTableYf: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '费用状态',
            key: 'status',
            type: FormTypes.normal,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '账单未建立'
          },
          {
            title: '费用名称',
            key: 'costName',
            type: FormTypes.slot,
            width: '200px',
            slotName: 'feeNameYf',
            // 表单验证规则
            validateRules: [
              {
                required: true, // 必填
                message: '${title}不能为空' // 提示的文本
              }
            ]
          },
          {
            title: '币种',
            key: 'currency',
            type: FormTypes.select,
            dictCode: 'currency',
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
            isReload: true,
            // 表单验证规则
            validateRules: [
              {
                required: true, // 必填
                message: '${title}不能为空' // 提示的文本
              }
            ]
          },
          {
            title: '结算单位',
            key: 'settlementCompany',
            width: '200px',
            type: FormTypes.slot,
            slotName: 'jsdwYf',
            isReload: true,
            // 表单验证规则
            validateRules: [
              {
                required: true, // 必填
                message: '${title}不能为空' // 提示的文本
              }
            ]
          },
          {
            title: '计费单位',
            key: 'chargingUnit',
            dictCode: 'billing_unit',
            type: FormTypes.sel_search,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            isReload: true,
            // 表单验证规则
            validateRules: [
              {
                required: true, // 必填
                message: '${title}不能为空' // 提示的文本
              }
            ]
          },
          {
            title: '数量',
            key: 'num',
            type: FormTypes.inputNumber,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '1',
            isCalc: true,
            buisName: 'costDetail',
            validateRules: [{ pattern: 'z', message: '${title}格式不正确' }]
          },
          {
            title: '单价',
            key: 'price',
            type: FormTypes.inputNumber,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '0',
            isCalc: true,
            buisName: 'costDetail',
            validateRules: [{ pattern: 'money', message: '${title}格式不正确' }]
          },
          {
            title: '总价',
            key: 'totalPrice',
            type: FormTypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '0',
            statistics: true
          },
          // {
          //   title: '总金额(CNY)',
          //   key: 'cnyAmount',
          //   type: FormTypes.normal,
          //   width: '100px',
          //   placeholder: '请输入${title}',
          //   defaultValue: '0'
          // },
          {
            title: '汇率',
            key: 'rate',
            type: FormTypes.input,
            width: '80px',
            isCalc: true,
            buisName: 'costDetail',
            placeholder: '${title}',
            defaultValue: '1',
            validateRules: [{ required: true, pattern: 'n', message: '${title}格式不正确' }]
          },
          {
            title: '开票汇率',
            key: 'invoiceRate',
            type: FormTypes.input,
            width: '150px',
            placeholder: '请输入${title}',
            defaultValue: '1',
            validateRules: [{ pattern: 'n', message: '${title}格式不正确' }]
          },
          {
            title: '账单类型',
            key: 'billType',
            type: FormTypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '应付'
          },
          // {
          //   title: '',
          //   key: 'type',
          //   type: FormTypes.normal,
          //   width: '0px',
          //   placeholder: '请输入${title}',
          //   defaultValue: 'yf',
          //   disabled:true
          // },
          {
            title: '账单号',
            key: 'billNumber',
            type: FormTypes.normal,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '发票号',
            key: 'invoiceNumber',
            type: FormTypes.normal,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '备注',
            key: 'remark',
            type: FormTypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          }
        ]
      },
      url: {
        add: '/box.trade/jzxTrade/add',
        edit: '/box.trade/jzxTrade/edit',
        queryById: '/box.trade/jzxTrade/queryById',
        jzxDefaultCostDetails: {
          list: '/box.trade/jzxTrade/queryJzxDefaultCostDetailsByMainId'
        },
        costInfoYs: {
          list: '/box.trade/jzxTrade/queryCostInfoByMainId'
        },
        costInfoYf: {
          list: '/box.trade/jzxTrade/queryCostInfoByMainId'
        }
      },
      companyData: [],
      status: false,
      boxId: '',
      yardInfoOptions: [],
      leaveDate: '',
      returnBoxDate: '',
      daysCost: 0,
      everyItemCost: 0,
      feeNameData: []

    }
  },
  props: {
    type: {
      type: String,
      required: true,
      default: '0'
    },
    //流程表单data
    formData: {
      type: Object,
      default: () => {
      },
      required: false
    },
    //表单模式：false流程表单 true普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    }

  },
  created() {
    //如果是流程中表单，则需要加载流程表单data
    this.initSelectOptions()
  },
  mounted() {
    this.initDictData()
  },
  methods: {
    //初始化堆场费率数据
    initSelectOptions() {
      let a = Vue.ls.get('Login_Userinfo')
      this.orgCode = a.orgCode
      ajaxGetDictItems('yard_info,yard_info_col,id,sys_org_code=\'' + a.orgCode + '\'', null).then((res) => {
        if (res.success) {
          this.yardInfoOptions = res.result
        }
      })
      let param = { isLock: 0, pageSize: 99999 }
      getAction('/fee/list', param).then(res => {
        console.log(res.result)
        let feeData = []
        for (let i = 0; i < res.result.length; i++) {
          feeData.push({
            value: res.result[i].feeName,
            text: res.result[i].feeName
          })
        }
        this.feeNameData = feeData
      })
      ajaxGetDictItems('soc', null).then(res => {
        if (res.success) {
          res.result.forEach(item => {
            this.socOptions.push(item.value)
          })
        }
      })

    },
    //堆场费率下拉筛选
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    //选择箱型时按需计算
    getBoxType(v) {
      this.daysCost = 0
      this.otherCost = 0
      this.everyItemCost = 0
      let yardCurrency = ''
      let isCalc = true
      for (let i = 0; i < this.jzxDefaultCostDetailsTable.dataSource.length; i++) {
        if (yardCurrency == '') {
          yardCurrency = this.jzxDefaultCostDetailsTable.dataSource[i].currency
        }
        //判断堆场费率的币种是否相同
        if (this.jzxDefaultCostDetailsTable.dataSource[i].currency == yardCurrency) {
          if (this.jzxDefaultCostDetailsTable.dataSource[i].unit2 == 'Day' && v == this.jzxDefaultCostDetailsTable.dataSource[i].unit1) {
            this.daysCost += this.jzxDefaultCostDetailsTable.dataSource[i].price
          }
          if (this.jzxDefaultCostDetailsTable.dataSource[i].unit2 == v && v == this.jzxDefaultCostDetailsTable.dataSource[i].unit1) {
            this.everyItemCost = this.everyItemCost + this.jzxDefaultCostDetailsTable.dataSource[i].price
          }
          if (this.jzxDefaultCostDetailsTable.dataSource[i].unit2 == 'sequence' && v == this.jzxDefaultCostDetailsTable.dataSource[i].unit1) {
            this.otherCost = this.otherCost + this.jzxDefaultCostDetailsTable.dataSource[i].price
          }
        } else {
          isCalc = false
          this.podYardTotalCostTips = '堆场费率币种不一致'
          break
        }

      }
      if (isCalc) {
        console.log(this.daysCost)
        console.log(this.otherCost)
        console.log(this.everyItemCost)
        let dayDiff = this.DateDiff(this.leaveDate, this.returnBoxDate) ? this.DateDiff(this.leaveDate, this.returnBoxDate) : 0
        // console.log(dayDiff)
        // console.log(((dayDiff + 1) * this.daysCost) + this.otherCost + this.everyItemCost)
        // if (this.daysCost == 0) {
        //   this.form.setFieldsValue({ 'podYardTotalCost': 0.00 })
        // } else {
        this.bizhong = yardCurrency
        // console.log(dayDiff)
        // console.log(this.daysCost)
        // console.log(this.otherCost)
        // console.log(this.everyItemCost)
        this.form.setFieldsValue({ 'podYardTotalCost': ((dayDiff + 1) * this.daysCost + this.otherCost + this.everyItemCost).toFixed(2) })
        // }
        this.calcProfit()
      } else {
        this.form.setFieldsValue({ 'podYardTotalCost': 0.00 })
        this.bizhong = ''
      }

    },
    //选择堆场然后查询相应的费率信息
    changeYardOption(value) {
      if (value) {
        let params = { id: value }
        this.jzxDefaultCostDetailsTable.loading = true
        this.confirmLoading = true
        getAction(this.url.jzxDefaultCostDetails.list, params).then((res) => {
          if (res.success) {
            this.daysCost = 0
            this.otherCost = 0
            this.everyItemCost = 0
            let yardCurrency = ''
            let isCalc = true
            this.jzxDefaultCostDetailsTable.dataSource = res.result
            for (let i = 0; i < res.result.length; i++) {
              if (yardCurrency == '') {
                yardCurrency = this.jzxDefaultCostDetailsTable.dataSource[i].currency
              }
              //判断堆场费率的币种是否相同
              if (this.jzxDefaultCostDetailsTable.dataSource[i].currency == yardCurrency) {
                if (res.result[i].unit2 == 'Day' && this.form.getFieldValue('containerType') == res.result[i].unit1) {
                  this.daysCost += res.result[i].price
                }
                if (res.result[i].unit2 == this.form.getFieldValue('containerType') && this.form.getFieldValue('containerType') == res.result[i].unit1) {
                  this.everyItemCost = this.everyItemCost + res.result[i].price
                }
                if (res.result[i].unit2 == 'sequence' && this.form.getFieldValue('containerType') == res.result[i].unit1) {
                  this.otherCost = this.otherCost + res.result[i].price
                }
              } else {
                isCalc = false
                this.podYardTotalCostTips = '堆场费率币种不一致'
                this.form.setFieldsValue({ 'podYardTotalCost': '' })
                break
              }
            }
            if (isCalc) {
              let dayDiff = this.DateDiff(this.leaveDate, this.returnBoxDate) ? this.DateDiff(this.leaveDate, this.returnBoxDate) : 0
              console.log(this.daysCost)
              console.log(this.otherCost)
              console.log(this.everyItemCost)
              console.log(dayDiff)
              // let dayDiff = this.DateDiff(this.leaveDate, this.returnBoxDate)
              // if (this.daysCost == 0) {
              //   this.form.setFieldsValue({ 'podYardTotalCost': 0.00 })
              // } else {
              this.bizhong = yardCurrency
              this.form.setFieldsValue({ 'podYardTotalCost': ((dayDiff + 1) * this.daysCost + this.otherCost + this.everyItemCost).toFixed(2) })
              // }
              this.calcProfit()
            } else {
              this.bizhong = ''
              this.form.setFieldsValue({ 'podYardTotalCost': 0.00 })
            }
          }
          this.jzxDefaultCostDetailsTable.loading = false
          this.confirmLoading = false
        })
      } else {
        this.bizhong = ''
        this.podYardTotalCostTips = ''
        this.daysCost = 0
        this.otherCost = 0
        this.everyItemCost = 0
        this.form.setFieldsValue({ 'podYardTotalCost': 0 })
        this.jzxDefaultCostDetailsTable.dataSource = []
      }

    },
    initDictData() {
      let param = { isLock: 0, pageSize: 99999 }
      getAction('/companydata/list', param).then(res => {
        console.log(res.result.records)
        let companyDataList = []
        for (let i = 0; i < res.result.records.length; i++) {
          companyDataList.push({
            value: res.result.records[i].companyName,
            text: res.result.records[i].companyName
          })
        }
        this.companyData = companyDataList
      })
    },
    // addHandleCancel(e) {
    //   this.customerModalVisible = false
    //   this.newCustomerTitle = ''
    // },
    // addHandleOk(e) {
    //   // this.customerModalVisible = false
    //   let customerVal = this.newCustomerTitle.trim().replaceAll(' ', '')
    //   let url = '/box.common/add', method = 'post'
    //   let value = { 'customerTitle': customerVal }
    //   if (customerVal) {
    //     httpAction(url, value, method).then((res) => {
    //       if (res.success) {
    //         this.$message.success(res.message)
    //         this.customerModalVisible = false
    //         console.log(res.result)
    //         this.dictOptions.unshift({ 'value': res.result, 'text': customerVal, 'title': customerVal })
    //         this.form.setFieldsValue({ 'companyName': res.result })
    //       } else {
    //         this.$message.warning(res.message)
    //       }
    //     }).finally(() => {
    //       this.newCustomerTitle = ''
    //     })
    //   }
    // },
    addItem() {
      this.customerModalVisible = true
    },
    addBefore() {
      this.form.resetFields()
      this.jzxDefaultCostDetailsTable.dataSource = []
      this.costInfoTableYs.dataSource = []
      this.costInfoTableYf.dataSource = []
    },
    getAllTable() {
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      let fieldval = pick(this.model, 'profitCurrency', 'profitDescCurrency', 'podYardTotalCostDescCurrency', 'profitDesc', 'podYardTotalCostDesc', 'buyBoxCostCurrency', 'useBoxCostCurrency', 'saleBoxCostCurrency', 'intentionToSellBoxFeelCurrency', 'conditionType', 'podDeliveryTime', 'shipCompany', 'polDesc', 'podDesc', 'createBy', 'boxId', 'podStackingDays', 'intentionToSellBoxFeel', 'customerBusinessNumber', 'companyName', 'containerCode', 'containerNumber', 'containerType', 'pol', 'pod', 'polInTime', 'eta', 'etd', 'podReturnboxTime', 'podLeaveTime', 'podYardInfo', 'buyBoxCost', 'useBoxCost', 'saleBoxCost', 'podYardTotalCost', 'profit', 'status', 'orderStartTime')
      this.$nextTick(() => {
        this.form.setFieldsValue(fieldval)
      })
      if (fieldval.pol) {
        fieldval.pol = { value: fieldval.pol, key: fieldval.pol }
      } else {
        delete fieldval['pol']
      }
      if (fieldval.pod) {
        fieldval.pod = { value: fieldval.pod, key: fieldval.pod }
      } else {
        delete fieldval['pod']
      }
      let intStatus = 0
      if (this.model.status) {
        intStatus = parseInt(this.model.status)
      }
      if (intStatus < 3) {
        this.status = true
        this.tableKeys = ['costInfoYs', 'costInfoYf']
      } else {
        this.tableKeys = ['jzxDefaultCostDetails']
        this.status = false
      }
      if (this.model.podYardInfo) {
        this.changeYardOption(this.model.podYardInfo)
      }
      // 加载子表数据
      if (this.model.id) {
        this.returnBoxDate = this.model.podReturnboxTime
        this.leaveDate = this.model.podLeaveTime
        // let params = { id: this.model.id, type: 'ys' }
        // let params1 = { id: this.model.id, type: 'yf' }
        // // this.requestSubTableData(this.url.jzxDefaultCostDetails.list, params, this.jzxDefaultCostDetailsTable)
        // this.requestSubTableDataOt(this.url.costInfoYs.list, params, this.costInfoTableYs)
        // this.requestSubTableDataOt(this.url.costInfoYf.list, params1, this.costInfoTableYf)
      }
    },
    save() {
      this.form.validateFields((err, values) => {
        if (!err) {
          let url = this.url.edit
          let method = 'put'
          let formData = values
          if (this.model.id) {
            values['id'] = this.model.id
          } else {
            url = this.url.add
            method = 'post'
            // values['boxId'] = this.boxId
            values['type'] = this.type
          }
          if (formData.pol) {
            formData.pol = formData.pol.value
          }
          if (formData.pod) {
            formData.pod = formData.pod.value
          }
          //利润额币种
          formData.profitCurrency = this.lirunbizhong
          //堆场总费用币种
          formData.podYardTotalCostCurrency = this.bizhong
          this.confirmLoading = true
          httpAction(url, values, method).then((res) => {
            if (res.success) {
              this.$message.success(res.message)
              //添加完后把返回的ID赋值给model.id
              if (method == 'post') {
                this.model.id = res.result
                this.$emit('ok', res.result)
              }
              // this.close()
            } else {
              this.$message.warning(res.message)
            }
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    },
    reloadChildTabData(ids, billNumber, datas) {
      let ysListIds = []
      let yfListIds = []
      let billType = datas[0].billType
      if (billType == '应收') {
        datas.forEach((item, index) => {
          if (ids.indexOf(item.id) > -1) {
            ysListIds.push(item.id)
            item.status = '未开票未核销'
            item.billNumber = billNumber
          }
        })
        this.costInfoTableYs.dataSource = datas
        this.disabledRowsYs = { 'id': ysListIds }
      } else if (billType == '应付') {
        datas.forEach((item, index) => {
          if (ids.indexOf(item.id) > -1) {
            yfListIds.push(item.id)
            item.status = '未开票未核销'
            item.billNumber = billNumber
          }
        })
        this.costInfoTableYf.dataSource = datas
        this.disabledRowsYf = { 'id': yfListIds }
      }
    },
    /** 查询某个tab的数据 */
    requestSubTableDataOt(url, params, tab, type, success) {
      tab.loading = true
      getAction(url, params).then(res => {
        let { result } = res
        let dataSource = []
        if (result) {
          if (Array.isArray(result)) {
            dataSource = result
          } else if (Array.isArray(result.records)) {
            dataSource = result.records
          }
        }
        tab.dataSource = dataSource
        this.aaa()
        tab.loading = false
      }).finally(() => {
        tab.loading = false
      })
    },
    aaa() {
      let ysListIds = []
      let yfListIds = []
      this.costInfoTableYs.dataSource.forEach((data, index) => {
        if (data.status !== '账单未建立') {
          ysListIds.push(data.id)
        }
      })
      this.costInfoTableYf.dataSource.forEach((data, index) => {
        if (data.status !== '账单未建立') {
          yfListIds.push(data.id)
        }
      })
      this.disabledRowsYf = { 'id': yfListIds }
      this.disabledRowsYs = { 'id': ysListIds }
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      console.log(allValues)
      this.getAllTable().then(tables => {
        /** 一次性验证主表和所有的次表 */
        return validateFormAndTables(this.form, tables)
      }).then(allValues => {
        if (typeof this.classifyIntoFormData !== 'function') {
          throw this.throwNotFunction('classifyIntoFormData')
        }
        console.log(allValues)
      }).catch(e => {
        if (e.error === VALIDATE_NO_PASSED) {
          // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
          this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
        } else {
          console.error(e)
        }
      })
      allValues.formValue['boxId'] = this.boxId
      allValues.formValue['type'] = this.type
      if (allValues.formValue.pol) {
        allValues.formValue.pol = allValues.formValue.pol.value
      }
      if (allValues.formValue.pod) {
        allValues.formValue.pod = allValues.formValue.pod.value
      }
      allValues.formValue.profitCurrency = this.lirunbizhong
      let main = Object.assign(this.model, allValues.formValue)
      console.log(allValues)
      if (this.status) {
        return {
          ...main, // 展开
          // jzxDefaultCostDetailsList: allValues.tablesValue[0].values,
          costInfoListYs: allValues.tablesValue[0].values,
          costInfoListYf: allValues.tablesValue[1].values
        }
      } else {
        return {
          ...main // 展开
          // jzxDefaultCostDetailsList: allValues.tablesValue[0].values
        }
      }

    },
    //渲染流程表单数据
    // showFlowData() {
    //   if (this.formBpm === true) {
    //     let params = { id: this.formData.dataId }
    //     getAction(this.url.queryById, params).then((res) => {
    //       if (res.success) {
    //         this.edit(res.result)
    //       }
    //     })
    //   }
    // },
    validateError(msg) {
      this.$message.error(msg)
    },
    // popupCallback(row) {
    //   this.confirmLoading = true
    //   this.boxId = row.boxId
    //   this.form.setFieldsValue(pick(row, 'buyBoxCostCurrency', 'useBoxCostCurrency', 'saleBoxCostCurrency', 'intentionToSellBoxFeelCurrency', 'conditionType', 'podDeliveryTime', 'shipCompany', 'polDesc', 'podDesc', 'createBy', 'boxId', 'podStackingDays', 'intentionToSellBoxFeel', 'customerBusinessNumber', 'companyName', 'containerCode', 'containerNumber', 'containerType', 'pol', 'pod', 'polInTime', 'eta', 'etd', 'podReturnboxTime', 'podLeaveTime', 'podYardInfo', 'podYardCostRate', 'buyBoxCost', 'useBoxCost', 'saleBoxCost', 'podYardTotalCost', 'profit', 'status', 'orderStartTime'))
    //   this.confirmLoading = false
    // },
    getLevelDate: function(v) {
      this.leaveDate = v
      if (this.returnBoxDate != '') {
        let diffDay = this.DateDiff(v, this.returnBoxDate) ? this.DateDiff(v, this.returnBoxDate) : 0
        if (diffDay + 1 < 0) {
          this.returnBoxDate = ''
          this.$message.warning('还空箱时间不能早于离场时间')
          this.form.setFieldsValue({ 'podReturnboxTime': '' })
          this.form.setFieldsValue({ 'podLeaveTime': '' })
          if (this.podYardTotalCostTips == '') {
            this.form.setFieldsValue({ 'podYardTotalCost': 0.00 })
          }
        } else {
          console.log(diffDay)
          this.form.setFieldsValue({ 'podStackingDays': diffDay + 1 })
          // if (this.daysCost == 0) {
          //   this.form.setFieldsValue({ 'podYardTotalCost': 0.00 })
          // } else {
          if (this.podYardTotalCostTips == '') {
            this.form.setFieldsValue({ 'podYardTotalCost': ((diffDay + 1) * this.daysCost + this.otherCost + this.everyItemCost).toFixed(2) })
            this.calcProfit()
          }
          // }
        }
      }
    },
    getReturnBoxDate(v) {
      this.returnBoxDate = v
      if (this.leaveDate != '') {
        let diffDay = this.DateDiff(this.leaveDate, v) ? this.DateDiff(this.leaveDate, v) : 0
        if (diffDay + 1 < 0) {
          this.leaveDate = ''
          this.$message.warning('还空箱时间不能早于离场时间')
          this.form.setFieldsValue({ 'podReturnboxTime': '' })
          this.form.setFieldsValue({ 'podLeaveTime': '' })
          if (this.podYardTotalCostTips == '') {
            this.form.setFieldsValue({ 'podYardTotalCost': 0.00 })
          }
        } else {
          this.form.setFieldsValue({ 'podStackingDays': diffDay + 1 })
          // if (this.daysCost == 0) {
          //   this.form.setFieldsValue({ 'podYardTotalCost': 0.00 })
          // } else {
          if (this.podYardTotalCostTips == '') {
            this.form.setFieldsValue({ 'podYardTotalCost': ((diffDay + 1) * this.daysCost + this.otherCost + this.everyItemCost).toFixed(2) })
            this.calcProfit()
          }

          // }
        }
      }
    },
    //选择币种-卖
    saleBoxSelectCurrency(v) {
      this.form.setFieldsValue({ 'saleBoxCostCurrency': v })
      this.calcProfit()
    },
    //用
    useBoxSelectCurrency(v) {
      this.form.setFieldsValue({ 'useBoxCostCurrency': v })
      this.calcProfit()
    },
    //买
    buyBoxSelectCurrency(v) {
      this.form.setFieldsValue({ 'buyBoxCostCurrency': v })
      this.calcProfit()
    },
    //堆场总费用
    podCostSelectCurrency(v) {
      this.form.setFieldsValue({ 'podYardTotalCostDescCurrency': v })
      this.calcProfit()
    },
    //计算利润额
    calcProfit() {
      this.confirmLoading = true
      let userBoxCost = this.form.getFieldValue('useBoxCost')
      let buyBoxCost = this.form.getFieldValue('buyBoxCost')
      let saleBoxCost = this.form.getFieldValue('saleBoxCost')
      //买卖用的币种
      let useBoxCostCurrency = this.form.getFieldValue('useBoxCostCurrency')
      let buyBoxCostCurrency = this.form.getFieldValue('buyBoxCostCurrency')
      let saleBoxCostCurrency = this.form.getFieldValue('saleBoxCostCurrency')
      let podYardTotalCostCurrency = this.form.getFieldValue('podYardTotalCostDescCurrency')
      let podYardTotalCostDesc = this.form.getFieldValue('podYardTotalCostDesc')
      let isCalc = true
      if (useBoxCostCurrency != buyBoxCostCurrency
        || useBoxCostCurrency != saleBoxCostCurrency
      ) {
        //买卖用的币种不一样
        isCalc = false
      } else {
        if (podYardTotalCostDesc) {
          if (useBoxCostCurrency != podYardTotalCostCurrency) {
            //自定义堆场总费用的币种与买卖用的不一样
            isCalc = false
          }
        } else {
          //TODO 如果没有自动计算除堆场总费用的情况下利润额也不进行计算
          if (useBoxCostCurrency != this.bizhong) {
            //计算出来的堆场总费用币种与买卖用的币种不一样
            isCalc = false
          }
        }
      }
      if (isCalc) {
        //目的港堆场总费用
        let podYardTotalCost = this.form.getFieldValue('podYardTotalCost')
        if (isNaN(podYardTotalCost)) {
          podYardTotalCost = 0
          this.form.setFieldsValue({ 'podYardTotalCost': 0.00 })
        }
        console.log(podYardTotalCostDesc ? podYardTotalCostDesc : podYardTotalCost)
        console.log(saleBoxCost + userBoxCost - buyBoxCost - (podYardTotalCostDesc ? podYardTotalCostDesc : podYardTotalCost))
        let profit = saleBoxCost + userBoxCost - buyBoxCost - (podYardTotalCostDesc ? podYardTotalCostDesc : podYardTotalCost)
        this.form.setFieldsValue({ 'profit': profit })
        this.profixTips = ''
        this.lirunbizhong = useBoxCostCurrency
      } else {
        this.profixTips = '各项费用币种不一致'
        this.lirunbizhong = ''
        this.form.setFieldsValue({ 'profit': '' })
      }
      this.confirmLoading = false
    },

    DateDiff(sDate1, sDate2) {    //sDate1和sDate2是2002-12-18格式
      let aDate, oDate1, oDate2, iDays
      if (sDate1 != null && sDate2 != null) {
        aDate = sDate1.split('-')
        oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])    //转换为12-18-2002格式
        aDate = sDate2.split('-')
        oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])
        iDays = parseInt((oDate1 - oDate2) / 1000 / 60 / 60 / 24)    //把相差的毫秒数转换为天数
        return iDays
      } else {
        return -1
      }

    },
    containerCodeFilterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toUpperCase() >= input.toUpperCase()
      )
    },
    searchPort(val) {
      let params = { name: val }
      getAction(this.getPortDataUrl, params).then(res => {
        if (res.code == 200) {
          let data = []
          res.result.forEach(item => {
            data.push({
              value: item.wzm,
              text: item.showText
            })
          })
          this.portData = data
        }
      })
    },
    //起运港选择后回显
    portDataChangePol(value) {
      // console.log(value)
      let portEnName = value.label.toString().trim().substr(value.label.toString().trim().indexOf(',') + 1, value.label.toString().trim().length)
      this.form.setFieldsValue({ 'pol': { value: value.key, key: value.key + ' ' } })
      this.form.setFieldsValue({ 'polDesc': portEnName })
    },
    //目的港选择后回显
    portDataChangePod(value) {
      // console.log(value)
      let portEnName = value.label.toString().trim().substr(value.label.toString().trim().indexOf(',') + 1, value.label.toString().trim().length)
      this.form.setFieldsValue({ 'pod': { value: value.key, key: value.key + ' ' } })
      this.form.setFieldsValue({ 'podDesc': portEnName })
    },
    handleProChangeYs(value, id) {
      let values = [
        {
          rowKey: id,
          values: {
            'costName': value
          }
        }
      ]
      this.$refs.costInfoYs.setValues(values)
    },
    handleProChangeYf(value, id) {
      let values = [
        {
          rowKey: id,
          values: {
            'costName': value
          }
        }
      ]
      this.$refs.costInfoYf.setValues(values)
    },
    handleProChangeYsJsdw(value, id) {
      let values = [
        {
          rowKey: id,
          values: {
            'settlementCompany': value
          }
        }
      ]
      this.$refs.costInfoYs.setValues(values)
    },
    handleProChangeYfJsdw(value, id) {
      let values = [
        {
          rowKey: id,
          values: {
            'settlementCompany': value
          }
        }
      ]
      this.$refs.costInfoYf.setValues(values)
    }
  }
}
</script>

<style lang="less" scoped>
.plclass {
  &::placeholder {
    color: red;
  }
}

/deep/ .ant-table {
  max-height: 300px !important;
}

/deep/ .ant-row .ant-form-item {
  margin-bottom: 0px;
}
</style>
